package com.example.lg.aliplaydemo470.activity;

import android.graphics.SurfaceTexture;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.TextureView;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.FrameLayout;
import android.widget.ImageView;

import com.aliyun.player.AliListPlayer;
import com.aliyun.player.AliPlayerFactory;
import com.aliyun.player.IPlayer;
import com.aliyun.player.nativeclass.PlayerConfig;
import com.example.lg.aliplaydemo470.R;
import com.example.lg.aliplaydemo470.adapter.AliListAdapter;
import com.example.lg.aliplaydemo470.bean.VideoBean;
import com.example.lg.aliplaydemo470.utils.DataUtil;

import java.util.List;


/**
 * 列表播放功能
 */
public class AliListPlayerActivity extends AppCompatActivity {
    private RecyclerView mRecyclerView;

    AliListAdapter mAliListAdapter;
    AliListPlayer mVideoListPlayer;
    AliListPlayerActivity mActivity;

    /**
     * 是否在后台
     */
    private boolean mIsOnBackground;
    /**
     * 是否是暂停
     */
    private boolean mIsPause;


    TextureView mTextureView;//这个控件可以用来实现全屏无缝衔接播放 还没有实现 2020-09-02
    private LinearLayoutManager linearLayoutManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ali_list_player);
        mActivity = this;


        initView();
        initAliPlayer();

        initPlayerView(); //初始化播放界面和暂停/播放按钮

        initListener();

        initData();
    }


    private void initView() {
        mTextureView = findViewById(R.id.textureView);

        mRecyclerView = findViewById(R.id.mRecyclerView);
        linearLayoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(linearLayoutManager);
        mAliListAdapter = new AliListAdapter(this);
        mRecyclerView.setAdapter(mAliListAdapter);


    }

    private void initAliPlayer() {


        mVideoListPlayer = AliPlayerFactory.createAliListPlayer(this);

        //开启硬解
        mVideoListPlayer.enableHardwareDecoder(true);
        //设置播放器参数
        PlayerConfig config = mVideoListPlayer.getConfig();
        //停止之后清空画面。防止画面残留（建议设置）
        config.mClearFrameWhenStop = true;
        mVideoListPlayer.setConfig(config);
        //开启循环播放。短视频一般都是循环播放的
        mVideoListPlayer.setLoop(true);

        //开启自动播放。
        mVideoListPlayer.setAutoPlay(true);//注意这个一定要开启


        //设置预加载个数。此时会加载3个视频。当前播放的，和上下1个。
        mVideoListPlayer.setPreloadCount(1);
        mVideoListPlayer.setOnPreparedListener(new IPlayer.OnPreparedListener() {
            @Override
            public void onPrepared() {
                System.out.println("AliListPlayerActivity.onPrepared mIsPause=" + mIsPause + " mIsOnBackground=" + mIsOnBackground);
                if (!mIsPause && !mIsOnBackground) {
                    mVideoListPlayer.start();
                }
            }
        });


        //列表播放时一般都会有个封面，视频播起来之后，把封面隐藏，显示视频。
        mVideoListPlayer.setOnRenderingStartListener(new IPlayer.OnRenderingStartListener() {
            @Override
            public void onRenderingStart() {
                //视频第一帧开始渲染。此时可以隐藏封面
                /*if (mRecyclerView != null) {
                    AliListAdapter.ViewHolder mViewHolder = (AliListAdapter.ViewHolder) mRecyclerView.findViewHolderForLayoutPosition(mCurrentPosition);
                    if (mViewHolder != null) {
                        mViewHolder.getCoverView().setVisibility(View.GONE);
                    }
                }*/
            }
        });


    }

    private ImageView mPlayIconImageView;
    TextureView mListPlayerTextureView = null;
    private View mListPlayerContainer;
    /**
     * 手势监听器
     */
    private GestureDetector mGestureDetector;

    /**
     * 初始化播放View 关键代码，好好理解！！
     */
    private void initPlayerView() {
        mListPlayerContainer = View.inflate(this, R.layout.layout_list_player_view, null);

        mPlayIconImageView = mListPlayerContainer.findViewById(R.id.iv_play_icon);
        mListPlayerTextureView = mListPlayerContainer.findViewById(R.id.list_player_textureview);

        //TextureView
        mListPlayerTextureView.setSurfaceTextureListener(new TextureView.SurfaceTextureListener() {

            @Override
            public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int width, int height) {
                System.out.println("initPlayerView AliListPlayerActivity.onSurfaceTextureAvailable");
                Surface mSurface = new Surface(surfaceTexture);
                if (mVideoListPlayer != null) {
                    mVideoListPlayer.setSurface(mSurface);
                    mVideoListPlayer.redraw();
                }
            }

            @Override
            public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
                System.out.println("initPlayerView AliListPlayerActivity.onSurfaceTextureSizeChanged");
                if (mVideoListPlayer != null) {
                    mVideoListPlayer.redraw();
                }
            }

            @Override
            public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
                System.out.println("initPlayerView AliListPlayerActivity.onSurfaceTextureDestroyed");
                //这里一定要return false。这样SurfaceTexture不会被系统销毁
                //测试发现 返回 true 也没有什么影响
                return false;
            }

            @Override
            public void onSurfaceTextureUpdated(SurfaceTexture surface) {
                //System.out.println("initPlayerView AliListPlayerActivity.onSurfaceTextureUpdated");

            }
        });

        //手势监听器
        mGestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
            @Override
            public boolean onSingleTapConfirmed(MotionEvent e) {
                onPauseClick();
                return true;
            }

            @Override
            public boolean onDown(MotionEvent e) {
                return true;
            }
        });

        //播放列表界面的touch事件由手势监听器处理
        mListPlayerContainer.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                return mGestureDetector.onTouchEvent(motionEvent);
            }
        });

    }

    int mCurrentPosition = -1;

    private void initListener() {
        mAliListAdapter.setOnItemClickListener(new AliListAdapter.OnItemClickListener() {
            @Override
            public void OnItemClickListener(ViewGroup rootView, View view, int position) {
                System.out.println("AliListPlayerActivity.OnItemClickListener position=" + position);
                mCurrentPosition = position;
                startPlay(position);
            }
        });


        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);


                int firstVisibleItemPosition = linearLayoutManager.findFirstVisibleItemPosition();
                int lastVisibleItemPosition = linearLayoutManager.findLastVisibleItemPosition();

                if (mCurrentPosition >= 0) {
                    if (mCurrentPosition + 1 > firstVisibleItemPosition && mCurrentPosition - 1 < lastVisibleItemPosition) {
                        //可见范围
                        System.out.println("AliListPlayerActivity.onScrolled 可见范围");

                        ViewParent parent = mListPlayerContainer.getParent();
                        if (parent instanceof FrameLayout) {

                        } else {
                            if (mViewHolder != null) {
                                mViewHolder.getContainerView().addView(mListPlayerContainer);//, 0
                            }
                        }


                    } else {
                        //不可见范围
                        System.out.println("AliListPlayerActivity.onScrolled 不可见范围");
                        removePlayView();
                    }
                }


            }
        });


    }

    private void initData() {
        List<VideoBean> videoInfo = DataUtil.getVideoInfo();
        for (int i = 0; i < videoInfo.size(); i++) {
            //mVideoListPlayer.addUrl("视频URL", "视频唯一标识");
            mVideoListPlayer.addUrl(videoInfo.get(i).getVideoUrl(), i + "");
        }
        mAliListAdapter.setNewData(videoInfo);
    }

    AliListAdapter.ViewHolder mViewHolder;

    /**
     * 播放视频
     */
    private void startPlay(int position) {

        if (position < 0 || position > mAliListAdapter.getData().size()) {
            return;
        }
        //恢复界面状态
        mIsPause = false;
        mPlayIconImageView.setVisibility(View.GONE);
        mViewHolder = (AliListAdapter.ViewHolder) mRecyclerView.findViewHolderForLayoutPosition(position);

        removePlayView();
        if (mViewHolder != null) {
            mViewHolder.getContainerView().addView(mListPlayerContainer);//, 0
        }
        //防止退出后台之后，再次调用start方法，导致视频播放
        if (!mIsOnBackground) {
            //开始播放视频
            //mVideoListPlayer.moveTo("视频唯一标识") //URL源
            mVideoListPlayer.moveTo(position + "");
        }
    }

    private void removePlayView() {
        ViewParent parent = mListPlayerContainer.getParent();
        if (parent instanceof FrameLayout) {
            System.out.println("AliListPlayerActivity.startPlay");
            ((ViewGroup) parent).removeView(mListPlayerContainer);
            //mVideoListPlayer.stop();
            //mVideoListPlayer.setSurface(null);
        } else {
            System.out.println("AliListPlayerActivity.startPlay else");
        }
    }

    /**
     * 停止视频播放
     */
    private void stopPlay() {
        ViewParent parent = mListPlayerContainer.getParent();
        if (parent instanceof FrameLayout) {
            ((FrameLayout) parent).removeView(mListPlayerContainer);
        }
        mVideoListPlayer.stop();
        mVideoListPlayer.setSurface(null);
    }

    /**
     * 视频暂停/恢复的时候使用，
     */
    public void onPauseClick() {
        if (mIsPause) {
            resumePlay();
        } else {
            pausePlay();
        }
    }


    /**
     * activity不可见或者播放页面不可见时调用该方法
     */
    public void setOnBackground(boolean isOnBackground) {
        this.mIsOnBackground = isOnBackground;
        if (isOnBackground) {
            pausePlay();
        } else {
            resumePlay();
        }
    }

    /**
     * 暂停播放
     */
    private void pausePlay() {
        mIsPause = true;
        mPlayIconImageView.setVisibility(View.VISIBLE);
        mVideoListPlayer.pause();
    }

    /**
     * 恢复播放
     */
    private void resumePlay() {
        mIsPause = false;
        mPlayIconImageView.setVisibility(View.GONE);
        mVideoListPlayer.start();
    }

    /**
     * 销毁
     */
    public void destroy() {
        if (mVideoListPlayer != null) {
            mVideoListPlayer.stop();
            mVideoListPlayer.release();
        }
    }


    @Override
    protected void onStart() {
        super.onStart();
        setOnBackground(false);

    }

    @Override
    protected void onPause() {
        super.onPause();
        setOnBackground(true);
    }

    @Override
    protected void onStop() {
        super.onStop();
        setOnBackground(true);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        destroy();
    }


    //在onResume中处理退后台再进的情况
    /*@Override
    protected void onResume() {
        super.onResume();
        if (mVideoListPlayer != null && mSurface != null) {
            mVideoListPlayer.setSurface(mSurface);
            mVideoListPlayer.redraw();
        }
    }*/

    //退出界面，使用完播放器，需要释放播放器。否则会有内存泄漏。
    /*@Override
    protected void onDestroy() {
        super.onDestroy();
        //释放surface
        mVideoListPlayer.setSurface(null);
        //如果按照第4步使用了TextureView，那么还需要释放缓存的surface
        if (mSurface != null) {
            mSurface.release();
        }
        if (mSurfaceTexture != null) {
            mSurfaceTexture.release();
        }
        //释放播放器
        mVideoListPlayer.release();
    }*/
}


//                UrlSource urlSource = new UrlSource();
//                urlSource.setUri(mAliListAdapter.getData().get(position));
//                //urlSource.setUri("http://jzvd.nathen.cn/c6e3dc12a1154626b3476d9bf3bd7266/6b56c5f0dc31428083757a45764763b0-5287d2089db37e62345123a1be272f8b.mp4");
//                mVideoListPlayer.setDataSource(urlSource);
//                mVideoListPlayer.prepare();
//mVideoListPlayer.start();


 /*SurfaceView mSurfaceView;

    private void initTedd2() {
        mSurfaceView = new SurfaceView(mActivity);
        mSurfaceView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        SurfaceHolder holder = mSurfaceView.getHolder();

        holder.addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(SurfaceHolder surfaceHolder) {
                System.out.println("AliListPlayerActivityqq.surfaceCreated");
                if (mVideoListPlayer != null) {
                    mVideoListPlayer.setDisplay(surfaceHolder);
                    //防止黑屏
                    mVideoListPlayer.redraw();
                }
            }

            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
                System.out.println("AliListPlayerActivityqq.surfaceChanged");
                //画面大小变化的时候重绘界面，立即刷新界面
                mVideoListPlayer.redraw();
            }

            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {
                System.out.println("AliListPlayerActivityqq.surfaceDestroyed");
                if (mVideoListPlayer != null) {
                    // mVideoListPlayer.stop();
                    mVideoListPlayer.setDisplay(null);
                }
            }
        });

    }*/
